
package com.timber.util;

import java.sql.*;
import java.util.*;
import pv.jfcx.*;


public class UserTblColMgr
{
  public static final int	DESCENDING = 0;
  public static final int	ASCENDING  = 1;
  protected static Hashtable	userColsMap = new Hashtable();

  public static boolean isColumnSetupPresent( SLTableModel tm )
  {
    return userColsMap.containsKey( getCName( tm ) );
  }
  /**
   * read user specified column configuration from database
   * set columns in the table model
   *
   * @param tm SLTableModel
   */
  public static void setUpColumns( SLTableModel tm )
  {
    String cname = getCName(tm);
    //Util.log("[UserTblColMgr.setUpColumns()] CName: " + cname);

    Vector ret = ( Vector )userColsMap.get( cname );

    if( ret == null ) {
      ret = getUserColsFromDB( tm );
    }

    if ( ret != null) {
        tm.setColumnList( ret );
        setUpSortCols( tm );
    }
  }

  protected static Vector getUserColsFromDB( SLTableModel tm )
  {
    //  Try to get user columns from database
    String cname = getCName(tm);

    Vector ret = (Vector) userColsMap.get( cname );
    if (ret == null)
       ret = new Vector();
    else
       ret.clear();

    try
    {
      Connection con = Global.getDBConnection();

      Statement stmt = con.createStatement();

      String query =
	"common..p_GetTableColumns '" +
	Global.getUserName() +
	"', '" +
	cname +
	"'";

      ResultSet rs = null;//stmt.executeQuery( query );
      while( rs.next() )
      {
	//  Step thru each row and put the appropriate SLColumnDefinition
	//  in our vector and set its sort rank.
	int colId = rs.getInt( "ColumnId" );
	int sortPos = rs.getInt( "SortPos" );
	int sortAscendingInt = rs.getInt( "SortAscending" );
	boolean sortAscending = ( ( sortAscendingInt == ASCENDING ) ? true : false );
	SLColumnDefinition cd = tm.getById( colId );
	if( cd == null )
	{
	  //  If this happens - a column has probably been removed from a table
	  //  model's list of columns but still resides in the database list.
	  //  We should provide a way to clean these up in the database...
	  Util.error( "UserTblColMgr.getUserColsFromDB(): Column ID: " +
		      colId +
		      " for table model: " +
		      cname +
		      " not found in table model's known columns." );
	  continue;
	}
	cd.setSortPos( sortPos );
	cd.setSortAscending( sortAscending );
	ret.add( cd );
      }
    }
    catch( Exception e )
    {
      Util.error( "Caught exception in UserTblColMgr.getUserColsFromDB() - " + e.getMessage() );
    }

    //  If we get here and the vector length is 0 - just use the table model
    //  master list
    //  AV: modified to use *current* ColumnList - more consistent, needed for reports usage of this class
    if( ret.size() == 0 )
    {
        return null;
      /*
      ret = ( Vector )tm.getColumnList().clone();
      //Util.error( "[UserTblColMgr.getUserColsFromDB()]: Nothing in database for "+cname+": Using ColumnList with " + ret.size() + " item(s)");

      if (ret.size() == 0) {
         ret = ( Vector )tm.getMasterColumnList().clone();
         //Util.error( "[UserTblColMgr.getUserColsFromDB()]: Empty ColumnList: using MasterColumnList(Size: "+ret.size()+")");
      }
      */
    }

    userColsMap.put( cname, ret );

    return ret;
  }

  protected static void setUpSortCols( SLTableModel tm )
  {
    Vector cols = tm.getColumnList();
    int i = 0;
    for( Enumeration e = cols.elements(); e.hasMoreElements(); ++i )
    {
      int sortPos;
      boolean ascending;
      SLColumnDefinition cd = ( SLColumnDefinition )e.nextElement();
      sortPos = cd.getSortPos();
      ascending = cd.getSortAscending();
      if( sortPos != -1 )
	tm.setSortingAt( i, sortPos, ascending, PVTableModel.AUTO );
    }
  }

  public static void saveColumnSet( SLTableModel tm )
  {
    String userName = Global.getUserName();
    String cname = getCName(tm);
    String cmd1 =
      "exec common..p_DelTableColumnConfig '" +
      userName +
      "','" +
      cname +
      "'";
    String cmd2 = new String();
    Vector cols = tm.getColumnList();
    int i = 0;
    for( Enumeration e = cols.elements(); e.hasMoreElements(); ++i )
    {
      SLColumnDefinition cd = ( SLColumnDefinition )e.nextElement();
      if( cd.isVisible() )
      {
	int ascendingFlag = ( ( cd.getSortAscending() == true ) ? ASCENDING : DESCENDING );
	cmd2 +=
	  "exec common..p_InsTableColumnConfig '" +
	  userName +
	  "', '" +
	  cname +
	  "', " +
	  cd.getId() +
	  ", " +
	  i +
	  ", " +
	  cd.getSortPos() +
	  ", " +
	  ascendingFlag +
	  "\n";
      }
    }

    try
    {
      Connection con = Global.getDBConnection();

      Statement stmt = con.createStatement();

      stmt.execute( cmd1 );

      stmt.execute( cmd2 );
    }
    catch( Exception ex )
    {
      Util.error( "Caught exception in UserTblColMgr.saveColumnSet() - " + ex.getMessage() );
    }

    userColsMap.put( cname, cols );
    setUpSortCols( tm );
  }

  protected static String getCName(SLTableModel tm){
    return tm.getClass().getName() + tm.getClassNameId();
  }
}
